<template>
  <a-modal
      v-model:visible="visible"
      modal-class="modal-form"
      title-align="start"
      :title="title"
      :top="80"
      :width="500"
      :align-center="false"
      :draggable="true"
      :mask-closable="false"
      :unmount-on-close="true"
      :ok-button-props="{ disabled: loading }"
      :cancel-button-props="{ disabled: loading }"
      :on-before-ok="handlerOk"
      @close="handleClose"
  >
    <a-spin class="form-full" >
      <BhForm  ref="formRef" :columns="formColumns" :model-value="formModel" :options="options"></BhForm>
    </a-spin>
  </a-modal>
</template>

<script setup lang="ts">
import {useLoading} from '@/hooks/modules/useLoading';
import useVisible from '@/hooks/visible';
import { UpdateRequest, updateRows } from '@/api/system/level';
import { type Columns, BhForm, type Options } from '@/components/BhForm'

const options: Options = {
  form: { size: 'large' },
  btns: { hide: true },
}
const formColumns: Columns = reactive([
  {
    label: '职级名称',
    field: 'name',
    type: 'input',
    props: {
      placeholder: '请输入职级名称',
    },
    rules: [{ required: true, message: '请输入职级名称' }],
  },
  {
    label: '状态',
    field: 'status',
    type: 'switch',
    props: {
      type: 'round',
      checkedValue: 1,
      uncheckedValue: 2,
      checkedText: '正常',
      uncheckedText: '禁用',
    },
  },
  {
    label: '排序',
    field: 'sort',
    type: 'input-number',
  },
])
const { visible, setVisible } = useVisible();
const { loading, setLoading } = useLoading();
const isAddHandle = computed(() => !formModel.value.id)
const title = computed(() => (!isAddHandle.value ? '修改部门' : '新增部门'))
const defaultForm = (): UpdateRequest => {
  return {
    id: undefined,
    name: undefined,
    status: 1,
    sort: 50,
  };
};
const formRef = ref<InstanceType<typeof BhForm>>()
const formModel = ref<UpdateRequest>({});
const emits = defineEmits(['restart']);
const renderForm = (record: any) => {
  formModel.value = { ...record };
};
// 打开新增
const openAdd = () => {
  renderForm({ ...defaultForm() });
  setVisible(true);
};
// 打开修改
const openUpdate = (record: any) => {
  renderForm({ ...defaultForm(), ...record });
  setVisible(true);
};
defineExpose({ openAdd, openUpdate });

const handlerClear = () => {
  setLoading(false);
};
// 确定
const handlerOk = async () => {
  setLoading(true);
  try {
    // 验证参数
    const error = await formRef.value?.formRef?.validate()
    if (error)   return false;
    //  修改
    await updateRows(formModel.value);
    emits('restart');
    // 清空
    handlerClear();
    return true;
  } catch (e) {
    setLoading(false);
    return false
  } finally {
    setLoading(false);
  }
};
// 关闭
const handleClose = () => {
  handlerClear();
};
</script>

<style scoped lang="less"></style>
